package cn.tedu.luban.order.main.service;

import cn.tedu.luban.order.protocol.dto.OrderMessageDTO;
import com.tedu.inn.protocol.exception.BusinessException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
public class RocketMQMessageService implements MessageService{

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendDelayMessage(String orderNo) throws BusinessException {
        //组织message对象
        Message<String> message = MessageBuilder.withPayload(orderNo).build();
        //发送是同步还是异步：如果不采用同步很难处理数据一致的问题（发送失败了，订单和日志没有办法回退）
        //2.选择调用发送方式为同步消息
        //500 表示发送消息的超时时间，时间单位是毫秒，是Long类型。设置为500就表示如果超过了500毫秒消息没有成功发送，则认为发送失败
        //5 表示等级 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        SendResult result = rocketMQTemplate.syncSend("order_delay_topic", message, 500, 5);
        //SEND_OK
        if (!"SEND_OK".equals(result.getSendStatus().toString())){
            throw new BusinessException("000","消息发送失败");
        }
    }

    @Override
    public void sendFinishMessage(OrderMessageDTO dto) throws BusinessException {
        //1.组织message对象
        Message<OrderMessageDTO> message = MessageBuilder.withPayload(dto).build();

        //2.同步发送
        SendResult result = rocketMQTemplate.syncSend("order_finish_topic", message);

        //3.根据发送是否成功，决定是否抛出异常
        if (!"SEND_OK".equals(result.getSendStatus().toString())){
            throw new BusinessException("000","发送失败");
        }
    }
}
